package de.joergviola.mobj.client.database;

import java.util.logging.Logger;

import com.google.code.gwt.database.client.SQLError;
import com.google.code.gwt.database.client.SQLTransaction;
import com.google.gwt.user.client.Window;

import de.joergviola.mobj.shared.Entity;
import de.joergviola.mobj.shared.ObjectNotFoundException;
import de.joergviola.mobj.shared.Persistable;
import de.joergviola.mobj.shared.Schema;
import de.joergviola.mobj.shared.UnknownEntityException;

public class SchemaTransaction extends BaseTransaction {
	private static final Logger log = Logger.getLogger("Schema");

	private final Schema schema;

	public SchemaTransaction(Schema schema) {
		this.schema = schema;
	}

	@Override
	public void onTransactionStart(SQLTransaction tx) {
		for (Class<? extends Persistable> p : schema.getTypes()) {
			Entity<?> entity = schema.getEntity(p);
			CreateTable createTable = new CreateTable();
			// Tricky: createTable get called with type and name and is thus
			// able to do the job
			// The object returned is indeed irrelevant
			try {
				entity.getObject(createTable);
			} catch (ObjectNotFoundException e) {
			} catch (UnknownEntityException e) {
			}
			String sql = createTable.getSQL(entity.getEntityName());
			log.info(sql);
			tx.executeSql(sql, null);
		}
	}

	@Override
	public void onTransactionFailure(SQLError error) {
		Window.alert("Database init failed: " + error.getMessage());
	}
}
